﻿/*
The MIT License (MIT)
Copyright (c) 2013 kaveh.shahbazian@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Threading;

namespace Buddy
{
    /// <summary>
    /// a simple in-memory object cache with expiration and sliding
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <typeparam name="V"></typeparam>
    public class Cache<K, V>
    {
        readonly Dictionary<K, Entry<V>> _storage = new Dictionary<K, Entry<V>>();
        readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
        readonly Timer _timer;

        public Cache() : this(null) { }
        public Cache(TimeSpan? cleaningInterval)
        {
            if (cleaningInterval.HasValue)
            {
                _timer = new Timer(Cleaner, null, TimeSpan.FromMilliseconds(10), cleaningInterval.Value);
            }
        }

        void Cleaner(object o)
        {
            using (var defer = new Defer())
            {
                _lock.EnterWriteLock();
                defer.Also += () => _lock.ExitWriteLock();

                var dic = _storage;

                var expired = new List<K>();
                foreach (var kv in dic)
                {
                    if (kv.Value.Expired)
                    {
                        expired.Add(kv.Key);
                    }
                }

                foreach (var k in expired) dic.Remove(k);
            }
        }

        public V this[K key]
        {
            get
            {
                V v;
                TryGet(key, out v);
                return v;
            }
            set { Set(key, value); }
        }

        public bool TryGet(K key, out V val)
        {
            using (var defer = new Defer())
            {
                _lock.EnterReadLock();
                defer.Also += () => _lock.ExitReadLock();

                val = default(V);

                var dic = _storage;
                Entry<V> v;
                var b = dic.TryGetValue(key, out v);

                if (b)
                {
                    if (v.Expired)
                    {
                        dic.Remove(key);
                        return false;
                    }
                    else
                    {
                        val = v.Val;
                        return true;
                    }
                }
                else { return false; }
            }
        }

        public void Set(K key, V val)
        {
            using (var defer = new Defer())
            {
                _lock.EnterWriteLock();
                defer.Also += () => _lock.ExitWriteLock();

                var dic = _storage;

                dic[key] = new Entry<V>(val);
            }
        }

        public void Set(K key, V val, TimeSpan expirationOffset)
        {
            using (var defer = new Defer())
            {
                _lock.EnterWriteLock();
                defer.Also += () => _lock.ExitWriteLock();

                var dic = _storage;

                dic[key] = new Entry<V>(val, new TimeOffset(expirationOffset));
            }
        }

        public void Set(K key, V val, TimeSpan expirationOffset, TimeSpan slidingOffset)
        {
            using (var defer = new Defer())
            {
                _lock.EnterWriteLock();
                defer.Also += () => _lock.ExitWriteLock();

                var dic = _storage;

                dic[key] = new Entry<V>(val, new TimeOffset(expirationOffset, slidingOffset));
            }
        }

        public bool Remove(K key)
        {
            using (var defer = new Defer())
            {
                _lock.EnterWriteLock();
                defer.Also += () => _lock.ExitWriteLock();

                var dic = _storage;

                var b = dic.Remove(key);
                return b;
            }
        }

        public void Clear()
        {
            using (var defer = new Defer())
            {
                _lock.EnterWriteLock();
                defer.Also += () => _lock.ExitWriteLock();

                var dic = _storage;
                dic.Clear();
            }
        }

        public int Count
        {
            get
            {
                using (var defer = new Defer())
                {
                    _lock.EnterReadLock();
                    defer.Also += () => _lock.ExitReadLock();

                    var dic = _storage;
                    var c = dic.Count;

                    return c;
                }
            }
        }

        class Entry<E>
        {
            private Entry() { }
            public Entry(E v) : this(v, null) { }
            public Entry(E v, TimeOffset offset)
            {
                Val = v;
                Offset = offset;
            }

            E _val;
            public E Val
            {
                get
                {
                    if (Offset != null && Offset.Sliding.HasValue) Offset.Offset = Offset.Offset.Add(Offset.Sliding.Value);
                    return _val;
                }
                set { _val = value; }
            }
            public TimeOffset Offset { get; set; }
            public bool Expired { get { return Offset == null ? false : Offset.Expired; } }
        }

        class TimeOffset
        {
            public TimeOffset(TimeSpan offset) : this(offset, null) { }
            public TimeOffset(TimeSpan offset, TimeSpan? sliding) : this(offset, sliding, DateTime.Now) { }
            public TimeOffset(
                TimeSpan offset,
                TimeSpan? sliding,
                DateTime time)
            {
                Offset = offset;
                Sliding = sliding;
                Time = time;
            }

            public DateTime Time { get; set; }
            public TimeSpan Offset { get; set; }
            public TimeSpan? Sliding { get; set; }

            public bool Expired { get { return DateTime.Now > Time.Add(Offset); } }
        }
    }
}
